#include "head.h"
#include <complex.h>
#include <string.h>

typedef struct train_s{
    int length;
    char buf[1024];
}train_t;

void snd_cmd(int socketFd,command_t* command,user_t* user,char* arg){
    char* file_name = arg;//这个是用户的文件名字

    char path[128] = {0};
    strcpy(path,user->path);//这个地址是用户要存的path

    int user_id = atoi(user->user_id);//这里是user_id
    /* int user_id = 1; */
    send(socketFd,&user_id,sizeof(int),MSG_NOSIGNAL);
    
    char buf[64]={"sha1sum "};
    strcat(buf,file_name);
    FILE *pipe1 = popen(buf, "r");//计算两个文件的哈希值
    char buf1[1024] = {0};
    fread(buf1,1, sizeof(buf1), pipe1);
    strtok(buf1," ");
    pclose(pipe1);
    
    char buff[64]={"md5sum "};
    strcat(buff,file_name);
    FILE *pipe2 = popen(buff, "r");
    char buf2[1024] = {0};
    fread(buf2,1, sizeof(buf2), pipe2);
    strtok(buf2," ");
    pclose(pipe2);

    send(socketFd,buf1,40,MSG_NOSIGNAL);//文件哈希长度固定为40
    send(socketFd,buf2,32,MSG_NOSIGNAL);//文件哈希长度固定为32

    int file_fd = open(file_name,O_RDWR);
    ERROR_CHECK(file_fd,0,"open");

    struct stat stat_file;
    fstat(file_fd,&stat_file);
    send(socketFd,&stat_file.st_size,sizeof(int),MSG_NOSIGNAL);

    int path_len = strlen(path);
    send(socketFd,&path_len,sizeof(int),MSG_NOSIGNAL);
    send(socketFd,path,path_len,MSG_NOSIGNAL);

    int name_len = strlen(file_name);//发送文件名字和长度
    send(socketFd,&name_len,sizeof(int),MSG_NOSIGNAL);
    send(socketFd,file_name,name_len,MSG_NOSIGNAL);
    
    int type_len;
    char type[128] = {0};
    recv(socketFd,&type_len,sizeof(int),MSG_WAITALL);
    recv(socketFd,type,type_len,MSG_WAITALL);
    if(strcmp(type,"having") == 0){
        printf("用户已经拥有该文件\n");
    }else if(strcmp(type,"resume") == 0){
        printf("正在进行断点续传\n");

        int serverfile_len = 0;
        recv(socketFd,&serverfile_len,sizeof(int),MSG_WAITALL);

        off_t offset = 0;//从偏移量开始进行传送
        offset = (off_t) serverfile_len;
        sendfile(socketFd,file_fd,&offset,stat_file.st_size - serverfile_len);

    }else if(strcmp(type,"failed") == 0){
        printf("该文件名已经被其他文件使用,传输失败\n");
    }else if(strcmp(type,"new_file") == 0){
        printf("即将传输全部的文件\n");
        sendfile(socketFd,file_fd,NULL,stat_file.st_size);
    }else if(strcmp(type,"instand_transfer") == 0){
        printf("急速秒传成功\n");
    }
    return;

}



